package com.acheli.registry.network.packet;

import com.acheli.ACHeli;
import com.acheli.registry.config.CustomDataBus;
import com.acheli.registry.network.ACHMessages;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.simple.SimpleChannel;

import java.io.*;
import java.util.HashMap;
import java.util.function.Supplier;

public class GsonDefaultComponentReloadC2SPacket {
    // 添加字符串字段
    private final CompoundTag tag;

    // 从字节缓冲区解码
    public GsonDefaultComponentReloadC2SPacket(FriendlyByteBuf buf) {
        this.tag = buf.readNbt();
    }


    public GsonDefaultComponentReloadC2SPacket() {
        CustomDataBus.gsonDefaultComponentProvidersMap.clear();
        CustomDataBus.componentFLRegistryC2SPacketCacheList.clear();
        tag = new CompoundTag();
    }

    // 编码到字节缓冲区
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeNbt(tag);
    }

    private boolean handle(Supplier<NetworkEvent.Context> supplier) {
        ACHeli.LOGGER.info("GsonDefaultComponentReloadC2SPacket");
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            CustomDataBus.gsonDefaultComponentProvidersMap.clear();
            CustomDataBus.componentFLRegistryC2SPacketCacheList.clear();
        });
        return true;
    }

    public static void register(SimpleChannel channel) {
        channel.messageBuilder(GsonDefaultComponentReloadC2SPacket.class, ACHMessages.id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(GsonDefaultComponentReloadC2SPacket::new)
                .encoder(GsonDefaultComponentReloadC2SPacket::toBytes)
                .consumerMainThread(GsonDefaultComponentReloadC2SPacket::handle)
                .add();
    }
}